<style>
    .headinfo {margin-bottom: 5px;}
    .select2-results__option {padding: 0px;}
#filter1 td:nth-child(1) {width: 100px; }
#filter1 td {padding-bottom: 2px;}
#geofilter .form-control {width:100px;display: inline-block;}
#map .popover{max-width: 380px; }
.select2-selection { overflow: hidden !important; }
.select2-selection__rendered { white-space: normal !important; word-break: break-all !important; }
</style>

<div id="particleinfodiv" class="panel panel-default" style="margin-left: 50px;margin-right: 50px;display: none;
position: absolute;z-index: 100;">
  <div class="panel-body">
    <h3>总体介绍</h3>
    ECOTAXA的颗粒物模块旨在用来存储Underwater Vision Profiler（UVP）及LIIST设备获得的数据。 它可以：
<br>•	加载颗粒物数据，并将它们与已上传到EcoTaxa中并做好分类的浮游动物图片及CTD数据整合到一起
<br>•	从颗粒物数据中处理粒径谱
<br>•	根据界定的范围下载生成的颗粒物图谱，CTD和浮游动物数据
<br>•	可视化数据并通过互联网访问允许其优化
<h3>数据库状态</h3>
数据库可以具有不同的状态（私有、部分或完全可用）。 如果您无法查看或下载想要查看的数据，则可以使用“统计”显示中提供的链接，以联系不同的项目管理员和数据所有者。
<br>数据所有者会一直显示在您下载的数据库中。要获取更多信息或讨论文章发表问题请与他们联系。
<br>默认情况下，所有颗粒物和CTD数据都可以显示在图表部分，并能够下载有限分辨率的数据。
<br>除非数据所有者更改了延期，否则在数据获取的24个月后，就可获得完整的颗粒物和CTD数据。
<br>如果Ecotaxa相关项目已经注释并可见，除非数据所有者更改延期时间，否则从采集之日起36个月后即可获得经过验证的浮游动物数据。
<br>通过获得对Ecotaxa标注项目（仅针对UVP项目）的标注或管理权限，您可以访问任何数据库（项目）。
<br>有关浮游动物数据库的警告：显示和下载的数据库中仅包含已经过验证的部分（即专家已经人为检查过的部分）。请在统计信息页面以及与数据一起导出的数据摘要中检查验证率。可访问Ecotaxa项目以检查标注的质量。
    <h3>数据提供者信息</h3>
    此应用程序旨在简化LISST和UVP数据库的处理和显示。
    <br>可以使用移动实例（联系 <a href="mailto:marc.picheral@obs-vlfr.fr">marc.picheral@obs-vlfr.fr</a>) 对你的数据进行现场处理，但是在回到岸上时，必须再次在服务器实例上完成导入项目。
<br>我们建议保留延期的默认设置，以发布数据库并使相关的Ecotaxa项目可见。 这会使访问结果和图像可视化。

    <h3>引用和免责</h3>
    如果您在您的工作中使用EcoTaxa，我们将非常感激:
<br>•	您将它引用为：Picheral M, Colin S, Irisson J-O (2017). EcoTaxa, a tool for the taxonomic classification of images.
    <a href="http://ecotaxa.obs-vlfr.fr">http://ecotaxa.obs-vlfr.fr</a>.
<br>•	您可以考虑在下一笔拨款中预留一些资金来支持网站的维护和发展。与我们联系，来评估怎么做是合理且有用的。
<br>Ecotaxa的颗粒物模块由SOERE MOOSE资助
    <br>联系人： <a href="mailto:marc.picheral@obs-vlfr.fr">marc.picheral@obs-vlfr.fr</a> / 开发: <a href="http://www.altidev.com" target="_blank">Altidev</a>
<br>免责声明：EcoTaxa应用程序的管理者不负责保管您托管的图像和相关数据，即使他们尽了最大努力来保持应用程序的稳定和安全。
  </div>
</div>

<div style="margin: 2px;">

<link rel="stylesheet" href="/static/openlayers/ol.css" type="text/css">
  <table style="width: 100%">
    <tr>
      <td style="width: 400px;vertical-align: top;">
<form id="filt_form" class="form-group-sm">
<b>样品过滤器:</b>

{#----------- Début formulaire filtrage -------------#}
<table id="filter1" style="width: 95%">
  <tr><td></td>
    <td>
<table style="width:100%;" id="geofilter">
  <tr><td colspan="2" style="padding-left: 40px;">北 <input type="text" class="form-control" id="MapOutN"  name="MapN" value="{{ reqfields['MapN'] }}">
  <button type="button" class="btn btn-xs btn-primary pull-right" style="margin-right: 5px;margin-top: 3px;" onClick="DrawInputOnMap();">在地图上绘制选择</button>
  </td></tr>
  <tr >
    <td style="padding: 2px;white-space: nowrap;">西 <input type="text" class="form-control" id="MapOutW" name="MapW" value="{{ reqfields['MapW'] }}"></td>
    <td>东 <input type="text" class="form-control" id="MapOutE" name="MapE" value="{{ reqfields['MapE'] }}"></td></tr>
  <tr><td colspan="2" style="padding-left: 40px;">南 <input type="text" class="form-control" id="MapOutS" name="MapS" value="{{ reqfields['MapS'] }}">
    <button type="button" class="btn btn-xs btn-primary pull-right" style="margin-right: 5px;margin-top: 3px;" onClick="ClearGeoFilter();">清除</button>
  </td></tr>
</table>

    </td>
  </tr>
  <tr><td>日期</td><td><input class="form-control" type="text" style="width: 100px;display: inline-block" id="filt_fromdate" name="filt_fromdate"  autocomplete="off" placeholder="起" value="{{ reqfields['filt_fromdate'] }}">
		和 <input class="form-control" type="text" style="width: 100px;display: inline-block" id="filt_todate" name="filt_todate"  autocomplete="off" placeholder="止" value="{{ reqfields['filt_todate'] }}">
  <button type="button" class="btn btn-xs btn-primary pull-right" style="margin-right: 5px;margin-top: 3px;" onClick="ClearDateFilter();">清除</button>
  </td></tr>
  <tr><td>设备  </td><td><input class="form-control" type="text" style="width: 100px;display: inline-block;" id="filt_instrum" name="filt_instrum"  autocomplete="off" value="{{ reqfields['filt_instrum'] }}"></td></tr>
  <tr><td>剖面类型 </td><td>{{ form.filt_proftype(style="width:100px") }}</td></tr>
  <tr><td>Ecotaxa项目 </td><td>{{ form.filt_proj(style="width:100%") }}</td></tr>
  <tr><td>颗粒物项目 </td><td>{{ form.filt_uproj(style="width:100%") }}</td></tr>
</table>
<div style="margin-top: 5px">
  <button type="button" id="btfilt" class="btn btn-primary" onclick="DoSearch()" style="width: 140px;"><span class="glyphicon glyphicon-search"></span> 应用过滤</button>
  <button type="button" id="btfilt" class="btn btn-primary" onclick="DisplayAll()" style="width: 200px;"><span class="glyphicon glyphicon-erase"></span> 显示所有 </button>
<br>
  <button type="button" id="btfilt" class="btn btn-primary" onclick="DoExport()" style="margin-top: 5px;width: 140px;" {% if not  current_user.is_authenticated %}disabled{% endif %} ><span class="glyphicon glyphicon-export"></span> 导出选定对象</button>
  <button type="button" id="btfilt" class="btn btn-primary" onclick="ShowStat()" style="margin-top: 5px;width: 200px;"><span class="glyphicon glyphicon-signal"></span> 显示选定统计数据</button>
<br>
点颜色说明 <span class='glyphicon glyphicon-info-sign' onclick="$('#dotlegend').toggle()"></span> <br>
  <div id="dotlegend" style="display: none">
  <span style="color: black;"><b>私有</b> : 隐藏数据</span><br>
  <span style="color: red;"><b>可见</b> : 图表是可见的，CTD和颗粒物有限的导出权限</span><br>
  <span style="color: orange;"><b>可导出</b> : CTD&颗粒物完全可导出（浮游生物隐藏或消失）</span><br>
  <span style="color: green;"><b>可导出</b> : CTD&颗粒物&浮游生物完全可导出 </span><br>

</div>


</div>

</form>
</td>    {#----------- Fin formulaire filtrage -------------#}
<td style="vertical-align: top;position: relative;">
<div id="map" class="map" style="width: 100%; height: 450px;">
Displaying Map requires Internet Access to load map from https://services.arcgisonline.com
</div>
  <div id="samplecount" style="position: absolute;top: 430px; left:10px;font-weight: bold;">-</div>
</td></tr></table>
<div id="ajaxlog"></div>

{#----------- Debut formulaire Graphique -------------#}
<table style="width: 100%">
<tr><td style="width: 400px;vertical-align: top;padding-right: 10px">
<div class="panel panel-default" id="graphconfig" >
  <div class="panel-body" style="padding: 5px;">
  <b>图形组态</b>
    <button type="button" class="btn btn-sm btn-primary pull-right" onclick="ProcessDraw()"><span class="glyphicon glyphicon-ok"></span> 绘制图表</button>
    <br>
      <form id="formgraphconfig">
        简化颗粒物直方图 - <span id=redhelpericon class="glyphicon glyphicon-check" style="cursor: pointer" data-html="true" data-placement="bottom" data-content=""></span> <br>
          {{ form.gpr(style="width:100%") }}<br>
          详细颗粒物直方图 - <span id=dethelpericon class="glyphicon glyphicon-check" style="cursor: pointer" data-html="true" data-placement="bottom" data-content=""></span> <br>
          {{ form.gpd(style="width:100%") }}<br>
          CTD数据 - <span id=ctdhelpericon class="glyphicon glyphicon-check" style="cursor: pointer" data-html="true" data-placement="bottom" data-content=""></span> <br>
          {{ form.ctd(style="width:100%") }}<br>
{# ------- Depth ------------#}
<div style="width:70%;display: inline-block">
	<div class="form-group-sm">
		<label class="title">深度</label>
		<span title="正值。两个值都是必需的。每个对象都有一个最小和最大深度。两个值都必须在要显示对象的选定范围内。" data-toggle="tooltip" data-placement="right" class="glyphicon glyphicon-info-sign"></span>
		<a class="pull-right label label-default" style="padding: 1px 3px 3px 3px; margin-top: 5px;font-size: 90%;" href=# onclick='ClearDepths();return false;'>清除</a>

		<div class="form-inline">
			<div class="input-group" style="width: 49%" >
				<div class="input-group-addon"><span class="glyphicon glyphicon-triangle-bottom"></span></div>
				<input class="form-control" type="text" id="filt_depthmin" name="filt_depthmin" autocomplete="off" value="" placeholder="最小 [m]">
			</div>
			<div class="input-group" style="width: 49%">
				<div class="input-group-addon"><span class="glyphicon glyphicon-triangle-top"></span></div>
				<input class="form-control"  type="text" id="filt_depthmax" name="filt_depthmax" autocomplete="off" value=""  placeholder="最大 [m]">
			</div>
		</div>
	</div>
</div>
<div >
  <label class="title">X轴上的比例尺 : </label>
  <input type="radio" name="XScale" value="I" checked> 线性
  - <input type="radio" name="XScale" value="O"> Log
  - <input type="radio" name="XScale" value="S"> Symlog
</div>

{# ------- Taxo Filter ------------#}
<div >
	<div class="form-group-sm">
    <label class="title">已验证的浮游生物过滤器 </label>
		<a class="pull-right clear label label-default" href='javascript:ClearTaxo();' style="padding: 1px 3px 3px 3px; margin-top: 5px;font-size: 90%;" >清除</a>

        <select id="taxolb" name="taxolb" multiple="multiple" style="width: 100%"  autocomplete="off">  </select>
	</div>
</div>
<div >
  <input type="checkbox" id="taxochild" name="taxochild" value="1" style='margin:0;'>
  子目录的总丰度
</div>

<div class="FilterToggle" style="display:none;cursor:pointer;">
    <span onclick="$('.FilterToggle').toggle();"><span class="glyphicon glyphicon-triangle-right"></span>Show filters</span>
</div>


<link rel="stylesheet" href="/static/jstree/themes/default/style.min.css" />
<script src="/static/jstree/jstree.min.js"></script>


<style>
    .tree li a {
    padding-right:20px !important;
    background:url(icons/Star-icon.png) top right no-repeat;
}
.tree li.clicked a {
    padding-right:20px !important;
    background:url(icons/Star-icon.png) top right no-repeat #BEEBFF;
}
.tree li a.hover,
.tree li a:hover {
    padding-right:20px !important;
    background:url(icons/Star-icon.png) top right no-repeat #D8F0FA;
}
.taxo_tree_selected .v {background-color: #777777;}
</style>
<div id="jstreeexp">
      <ul>
    <li>Root node 1</li>
    <li>Root node 2</li>
  </ul>
  </div>

<script>
  $(function () {
    var jstreeexp=$('#jstreeexp');
    var taxolb=$('#taxolb');
    jstreeexp.jstree({
      'core': {
        "animation" : 0,
        "themes" : { "stripes" : false, "icons": false  },
        'data': {
            'dataType': 'JSON',
            'url': '/search/taxotreejson',
            'data': function (node) {
                return {'id': node.id};
            }
        }
      }
    });

      jstreeexp.delegate(".TaxoSel",'click',
          function(o){
            o.preventDefault();
            var id= $(o.target).closest("li").attr("id");
            var valeur= $(o.target).prev().html();
            if($(o.target).hasClass("glyphicon"))
                valeur= $(o.target).parent().prev().html();
           $('#SelectedID').html(id);
           $('#SelectedName').html(valeur);
           taxolb.append($('<option>', {    value: id,    text: valeur}));
            var sel=taxolb.val();
            if(sel===null) sel=[];
            sel.push(id);
            taxolb.val(sel);
            taxolb.change();
          });

    $("#jstree").bind("select_node.jstree", function (e, data) {
        $("#jstree").jstree('open_node', data.node);
    });
    {# Quand on ouvre une branche de l'arbre on met à jours les background pour les nouveaux noeuds  #}
    jstreeexp.on('after_open.jstree', function(){ $('#taxolb').change(); });

    taxolb.change(function (){ {# Mise à jour des background dans l'arbre #}
      $(".taxo_tree_selected").removeClass("taxo_tree_selected");
      var taxofilterarray = [];
      taxolb.find(':selected').each(function(i, selected){ taxofilterarray[i] = "#"+$(selected).val();    });
      $(taxofilterarray.join(",")).addClass("taxo_tree_selected");
    });

  });
  function ClearTaxo(){
  $( "#taxolb" ).val(null).trigger("change");
}
</script>
</form>
</div>
</div>
</td> {#----------- Fin formulaire Graphique -------------#}
<td style="vertical-align: top;"> {#----------- Zone destination du Graphique -------------#}
  <div id="graphdest" style="width: 100%;display: inline-block;"></div></td>
</tr></table></div>

<script>
$( "#filt_fromdate,#filt_todate" ).datepicker({
    showButtonPanel: true,changeMonth: true,changeYear: true,dateFormat:"yy-mm-dd"
  });
$('#filt_proj,#filt_uproj').select2({closeOnSelect:false});
$('#filt_proftype').select2({ minimumResultsForSearch: -1});
$('#gpr,#gpd,#ctd').select2( );

function DoSearch(){
{#    $('#ajaxlog').append("Start DoSearch");#}
    var url="/part/searchsample?"+$('#filt_form').serialize();
{#    $('#ajaxlog').append("<br>URL="+url);#}
    $.getJSON( url, function( data ) {
{#        $('#ajaxlog').append( "<br>" +data.length+" samples found");#}
        SampleSource.clear();SampleSourceNotVisible.clear();SampleSourceVisible.clear();SampleSourceExportCTD.clear();
        var d = new Date();
        $('#samplecount').html(data.length+" 个样品 - "+d.toUTCString()+"<span style='font-weight:normal'> - 使用 Shift+拖动进行矩形缩放，使用 Alt+拖动进行矩形选择</span>");
        $.each( data, function(key, val ) {
            var iconFeature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([val['long'],val['lat']], 'EPSG:4326','EPSG:3857'))
                      ,psampleid:val['id'] });
            if(val['visibility'][1]=='Y')
              SampleSource.addFeature(iconFeature);
            else if(val['visibility'][0]=='Y')
              SampleSourceExportCTD.addFeature(iconFeature);
            else if(val['visibility'][0]=='V')
              SampleSourceVisible.addFeature(iconFeature);
            else
              SampleSourceNotVisible.addFeature(iconFeature);
{#            $('#ajaxlog').append( "<br>-" + val['id']+val['lat']  );#}
          });
    });
}
function ShowStat() {
  var url="/part/statsample?"+$('#filt_form').serialize();
  $('#graphdest').html("<div id=waiter><img src='/static/spinningred.gif' >Processing your request, please wait....</div>"
      ).load(url, function( response, status, xhr ) {
        if ( status == "error" ) { $( "#graphdest" ).html( xhr.status + " " + xhr.statusText );  } });
}

function DisplayAll()
{
  $('#filt_form')[0].reset(); {# Efface tous les champs simples #}
  $("#filt_form select").each( function(){ $(this).val([]).change();}); {# Vide les select2 #}
  DrawInputOnMap();
  DoSearch();
}

function DoExport(){
  var url="/Task/Create/TaskPartExport?"+$('#filt_form').serialize()+"&"+$('#formgraphconfig').serialize();
  window.location=url;
}

function ProcessDraw(){
  var url="/part/drawchart?"+$('#filt_form').serialize()+"&"+$('#formgraphconfig').serialize()+"&r="+Math.random();
  var img = $("<div id=waiter><img src='/static/spinningred.gif' >Processing your request, please wait....</div><img src='"+url+"' style='max-width: 100%;'>");
  img.load(function() {
    $('#waiter').hide();
  });
  $('#graphdest').text('').append(img);
}

function ClearDepths(){
  $( "#filt_depthmin,#filt_depthmax" ).val("");
}

$(document).ready(function() {
  $("#taxolb").select2({
    ajax: {
      url: "/search/taxo",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {q: params.term, page: params.page};
      },
      processResults: function (data, page) {
        return {results: data};
      },
      cache: true
    },
    minimumInputLength: 3
  }); // Select2 Ajax
  $('[data-toggle="tooltip"]').tooltip();
  DoSearch();
});
</script>
{#------------- Gestion cartographie -------------------------#}
<script src="/static/openlayers/ol.js" type="text/javascript"></script>
<script>
var map,vectorSource,SampleSource,SampleSourceNotVisible,MapPopupContent;
function InitMap() {
  var attribution = new ol.Attribution({
        html: 'Tiles © <a href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer">ArcGIS</a>'
      });
var mousePositionControl = new ol.control.MousePosition({
  coordinateFormat: ol.coordinate.createStringXY(4),
  projection: 'EPSG:4326',
  undefinedHTML: '&nbsp;'
});
map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.XYZ({
              attributions: [attribution],
    {% if LocalGIS %}
        url: '/static/tiles/tile_{z}_{y}_{x}.jpg',maxZoom:6
    {% else %}
              url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}'
    {% endif %}
            })
    })
  ],
  controls: ol.control.defaults({
    attributionOptions:  ({
      collapsible: false
    })
  }).extend([mousePositionControl]),
  target: 'map',
  view: new ol.View({
    center: [0, 47],
    zoom: parseFloat($("#map").css('height'))/450 {# Mise à l'echelle, affiche toute la hauteur à l'echelle 1 sur une zone de 450px de haut #}
  })
});

// a DragBox interaction used to select features by drawing boxes
var dragBox = new ol.interaction.DragBox({
  condition: ol.events.condition.altKeyOnly,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({color: [0, 0, 255, 1]})
  })
});

map.addInteraction(dragBox);

dragBox.on('boxend', function(e) {
  var extent = dragBox.getGeometry().getExtent();
  // Calcule les tableau sous forme X/Longitude , Y/Lattitude
  var bottomleft= ol.proj.transform([extent[0], extent[1]], 'EPSG:3857', 'EPSG:4326') ;
  var topright= ol.proj.transform([extent[2], extent[3]], 'EPSG:3857', 'EPSG:4326') ;
  if((bottomleft[0]<-180)||(bottomleft[0]>180))
      bottomleft[0]=(bottomleft[0]+180+720)%360-180;
  if((topright[0]<-180)||(topright[0]>180))
      topright[0]=(topright[0]+180+720)%360-180;
  if(topright[0]<-180) topright[0]+=360;
  $("#MapOutN").val(topright[1].toFixed(4));
  $("#MapOutW").val(bottomleft[0].toFixed(4));
  $("#MapOutE").val(topright[0].toFixed(4));
  $("#MapOutS").val(bottomleft[1].toFixed(4));
  DrawInputOnMap();
});

// Create vector source and the feature to it.
vectorSource = new ol.source.Vector();
var vectorLayer= new ol.layer.Vector({  source: vectorSource });

var RedIconStyle = new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 0.5],
          size: [40, 40],
          offset: [52, 0],
          opacity: 1,
          scale: 0.19,
          src: '/static/dots2.png'
        })
      });
var OrangeIconStyle = new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 0.5],
          size: [40, 40],
          offset: [208, 0],
          opacity: 1,
          scale: 0.19,
          src: '/static/dots2.png'
        })
      });
var BlackIconStyle = new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 0.5],
          size: [40, 40],
          offset: [156, 0],
          opacity: 1,
          scale: 0.19,
          src: '/static/dots2.png'
        })
      });

var GreenIconStyle = new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 0.5],
          size: [40, 40],
          offset: [0, 0],
          opacity: 1,
          scale: 0.19,
          src: '/static/dots2.png'
        })
      });

SampleSource = new ol.source.Vector();
SampleSourceNotVisible= new ol.source.Vector();
SampleSourceVisible= new ol.source.Vector();
SampleSourceExportCTD= new ol.source.Vector();
var SampleLayer= new ol.layer.Vector({   source:SampleSource,style: GreenIconStyle });
var SampleNotVisibleLayer= new ol.layer.Vector({  source:SampleSourceNotVisible,style: BlackIconStyle });
var SampleVisibleLayer= new ol.layer.Vector({  source:SampleSourceVisible,style: RedIconStyle });
var SampleExportCTDLayer= new ol.layer.Vector({  source:SampleSourceExportCTD,style: OrangeIconStyle});
// Add the vector layer to the map.
map.addLayer(vectorLayer);
map.addLayer(SampleLayer);
map.addLayer(SampleNotVisibleLayer);
map.addLayer(SampleVisibleLayer);
map.addLayer(SampleExportCTDLayer);

var MapPopupElt = document.getElementById('MapPopup');
var popup = new ol.Overlay({
  element: MapPopupElt,
  positioning: 'bottom-center',
  stopEvent: false,
  offset: [3, 0]
});
map.addOverlay(popup);
// display popup on click
map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature) {
        return feature;
      });

  if (feature) {
    var coordinates = feature.getGeometry().getCoordinates();
{#    popup.setPosition(coordinates); Utilisation de l'evt plutot pour traiter le monde cyclique#}
    popup.setPosition(evt.coordinate);
{#    console.log(coordinates,evt.coordinate);#}
    MapPopupContent='Get Data for sample '+feature.get('psampleid');
    $(MapPopupElt).popover({
      'placement': 'right',
      'html': true,
      'content': function (){return MapPopupContent;}
    });
    $(MapPopupElt).popover('show');
    $.get('/part/getsamplepopover/'+feature.get('psampleid'),function(data){
      MapPopupContent=data;
      $(MapPopupElt).popover('show');
    });
  }
  else
    $(MapPopupElt).popover('destroy');
});

} //InitMap
function GetMapPopupContent(){
  return MapPopupContent;
}

function DrawSelectionRectangle(a){ {# X Y X Y  #}
  var ring = [ [a[0], a[1]], [a[2], a[1]],  [a[2], a[3]], [a[0], a[3]] , [a[0], a[1]] ];
  var polygon = new ol.geom.Polygon([ring]);
  polygon.transform('EPSG:4326', 'EPSG:3857');
  // Create feature with polygon.
  var feature = new ol.Feature(polygon);
  vectorSource.clear();
  vectorSource.addFeature(feature);
}

function DrawInputOnMap()
{
var MapOutW=parseFloat($("#MapOutW").val());
var MapOutN=parseFloat($("#MapOutN").val());
var MapOutE=parseFloat($("#MapOutE").val());
var MapOutS=parseFloat($("#MapOutS").val());
if(MapOutW>MapOutE) {
  DrawSelectionRectangle([MapOutW, MapOutN, MapOutE+360, MapOutS]);
} else {
  DrawSelectionRectangle([MapOutW, MapOutN, MapOutE, MapOutS]);
}
}
function ClearGeoFilter()
{
  $("#MapOutW,#MapOutN,#MapOutE,#MapOutS").val("");
  DrawInputOnMap();
}
function ClearDateFilter()
{
  $("#filt_fromdate,#filt_todate").val("");
}
$(function(){  {# Initialisation de la carte #}
 $("#map").html("");
  InitMap();
 });

$(function () {
{#  Gestion du popup de selection rapide réduit #}
  $('body').on("click","#redhelpertab td",function () {
    var begin=parseInt($(this).data('begin'));
    var end=parseInt($(this).data('end'));
    var rowtype=$(this).closest('tr').data('type');
    var i;
    var gpr=$('#gpr');
    if(end===0)
      gpr.find("option[value^='"+rowtype+"']").prop('selected',false);
    else
      for(i=begin;i<=end;i++)
        gpr.find("option[value='"+rowtype+i+"']").prop('selected',true);
    $("#redhelpericon").popover('hide');
    gpr.trigger('change');
  });
  var srcredhelpericon=$("#srcredhelpericon");
  $("#redhelpericon").data('content',srcredhelpericon.html()).popover();
  srcredhelpericon.remove();
{#  Gestion du popup de selection rapide détaillé #}
  $('body').on("click","#dethelpertab td",function () {
    var begin=parseInt($(this).data('begin'));
    var end=parseInt($(this).data('end'));
    var rowtype=$(this).closest('tr').data('type');
    var i;
    var gpr=$('#gpd');
    if(end===0)
      gpr.find("option[value^='"+rowtype+"']").prop('selected',false);
    else
      for(i=begin;i<=end;i++)
        gpr.find("option[value='"+rowtype+i+"']").prop('selected',true);
    $("#dethelpericon").popover('hide');
    gpr.trigger('change');
  });
  srcredhelpericon=$("#srcdethelpericon");
  $("#dethelpericon").data('content',srcredhelpericon.html()).popover();
  srcredhelpericon.remove();
{#  Gestion du popup de selection rapide CTD #}
  $('body').on("click","#ctdhelpertab td",function () {
    var begin=parseInt($(this).data('begin'));
    var i;
    var gpr=$('#ctd');
    if(begin===0)
      gpr.find("option").prop('selected',false);
    else
        gpr.find("option").prop('selected',true);
    $("#ctdhelpericon").popover('hide');
    gpr.trigger('change');
  });
  srcredhelpericon=$("#srcctdhelpericon");
  $("#ctdhelpericon").data('content',srcredhelpericon.html()).popover();
  srcredhelpericon.remove();
  DrawInputOnMap();
});
</script>
<div id='MapPopup'></div>
<style>
table.Grille{
   border-color:black;
   border-width:1px;
   border-style:solid;
   border-collapse:collapse;
}
table.Grille td,table.Grille th{
   border-width:1px;
   border-style:solid;
   border-color:black;
   padding: 2px 3px 2px 3px;
}
#redhelpertab td,#dethelpertab td,#ctdhelpertab td {cursor: pointer; text-decoration: underline;}
#formgraphconfig  .popover{  max-width: 100%;  }
</style>
<div id="srcredhelpericon">
  <table id="redhelpertab" class="Grille">
    <tr data-type="cl"><th>LPM</th>
      <td  data-begin="1" data-end="15">All</td>
      <td data-begin="1" data-end="6">Class 1-6</td>
      <td  data-begin="7" data-end="12">UVP class 7-12</td>
      <td  data-begin="0" data-end="0">None</td></tr>
    <tr data-type="bv"><th>BV</th>
      <td  data-begin="1" data-end="15">All</td>
      <td data-begin="1" data-end="6">Class 1-6</td>
      <td  data-begin="7" data-end="12">UVP class 7-12</td>
      <td  data-begin="0" data-end="0">None</td>
    </tr>
  </table>
</div>
<div id="srcdethelpericon">
  <table id="dethelpertab" class="Grille" style="width: 300px;">
    <tr data-type="cl"><th>LPM</th>
      <td  data-begin="1" data-end="45">All</td>
      <td data-begin="1" data-end="17">Class 1-17</td>
      <td  data-begin="18" data-end="45">UVP class 18-45</td>
      <td  data-begin="0" data-end="0">None</td></tr>
    <tr data-type="bv"><th>BV</th>
      <td  data-begin="1" data-end="45">All</td>
      <td data-begin="1" data-end="17">Class 1-17</td>
      <td  data-begin="18" data-end="45">UVP class 18-45</td>
      <td  data-begin="0" data-end="0">None</td>
    </tr>
  </table>
</div>
<div id="srcctdhelpericon">
  <table id="ctdhelpertab" class="Grille" style="width: 300px;">
    <tr >
      <td  data-begin="1" data-end="45">All</td>
      <td  data-begin="0" data-end="0">None</td></tr>
  </table>
</div>